"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Search, Plus, Edit, Trash2, AlertCircle } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { PostDialog } from "@/components/posts/post-dialog";

interface PostCount {
  id: number;
  countId: string;
  viewCount: number;
  likeCount: number;
  shareCount: number;
  commentCount: number;
}

interface Category {
  categoryId: number;
  categoryName: string | null;
}

interface User {
  openId: string;
  uName: string;
  avatarUrl: string;
}

interface Post {
  id: string;
  uId: string;
  images: string | null;
  content: string | null;
  categoryId: number | null;
  createTime: string;
  updateTime: string | null;
  status: number;
  user?: User;
  category?: Category | null;
  postCount?: PostCount | null;
}

export default function PostsPage() {
  const [posts, setPosts] = useState<Post[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");
  const [isLoading, setIsLoading] = useState(true);
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectedPost, setSelectedPost] = useState<Post | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [postToDelete, setPostToDelete] = useState<string | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [newPost, setNewPost] = useState({
    uId: "admin", // 默认使用管理员ID
    content: "",
    categoryId: "",
    images: "",
  });
  const [illegalWordsError, setIllegalWordsError] = useState<string[]>([]);
  const [checkedPosts, setCheckedPosts] = useState<{ [key: string]: string[] }>(
    {}
  );

  useEffect(() => {
    fetchPosts();
    fetchCategories();
  }, []);

  const fetchPosts = async () => {
    try {
      setIsLoading(true);
      const response = await fetch("/api/posts");

      if (!response.ok) {
        throw new Error("获取帖子数据失败");
      }

      const data = await response.json();
      setPosts(data.posts);
    } catch (error) {
      console.error("获取帖子数据失败:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchCategories = async () => {
    try {
      const response = await fetch("/api/categories");

      if (!response.ok) {
        throw new Error("获取分类数据失败");
      }

      const data = await response.json();
      setCategories(data.categories);
    } catch (error) {
      console.error("获取分类数据失败:", error);
    }
  };

  const handleCreatePost = async () => {
    try {
      if (!newPost.content) {
        alert("帖子内容不能为空");
        return;
      }

      const response = await fetch("/api/posts", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          uId: newPost.uId,
          content: newPost.content,
          categoryId: newPost.categoryId ? parseInt(newPost.categoryId) : null,
          images: newPost.images || null,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        if (data.illegalWords) {
          setIllegalWordsError(data.illegalWords);
          return;
        }
        throw new Error(data.error || "创建帖子失败");
      }

      setIsCreateDialogOpen(false);
      setNewPost({
        uId: "admin",
        content: "",
        categoryId: "",
        images: "",
      });
      setIllegalWordsError([]);
      fetchPosts();
    } catch (error) {
      console.error("创建帖子失败:", error);
      alert(error instanceof Error ? error.message : "创建帖子失败");
    }
  };

  const handleDeletePost = async () => {
    if (!postToDelete) return;

    try {
      const response = await fetch(`/api/posts?id=${postToDelete}`, {
        method: "DELETE",
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "删除帖子失败");
      }

      setIsDeleteDialogOpen(false);
      setPostToDelete(null);
      fetchPosts();
    } catch (error) {
      console.error("删除帖子失败:", error);
      alert(error instanceof Error ? error.message : "删除帖子失败");
    }
  };

  const handlePostSave = (updatedPost: Post) => {
    setPosts(
      posts.map((post) => (post.id === updatedPost.id ? updatedPost : post))
    );
  };

  // 过滤帖子
  const filteredPosts = posts.filter((post) => {
    // 搜索条件
    const matchesSearch =
      (post.content &&
        post.content.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (post.user &&
        post.user.uName.toLowerCase().includes(searchTerm.toLowerCase()));

    // 分类过滤
    const matchesCategory =
      categoryFilter === "all" ||
      (post.categoryId && post.categoryId.toString() === categoryFilter) ||
      (categoryFilter === "none" && !post.categoryId);

    // 状态过滤
    const matchesStatus =
      statusFilter === "all" || post.status.toString() === statusFilter;

    return matchesSearch && matchesCategory && matchesStatus;
  });

  // 获取帖子状态文本
  const getPostStatusText = (status: number) => {
    switch (status) {
      case 0:
        return "已禁用";
      case 1:
        return "正常";
      case 2:
        return "已置顶";
      default:
        return "未知状态";
    }
  };

  // 获取帖子状态样式
  const getPostStatusVariant = (status: number) => {
    switch (status) {
      case 0:
        return "destructive";
      case 1:
        return "default";
      case 2:
        return "success";
      default:
        return "secondary";
    }
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  // 截断内容
  const truncateContent = (content: string | null, maxLength: number = 50) => {
    if (!content) return "";
    return content.length > maxLength
      ? content.substring(0, maxLength) + "..."
      : content;
  };

  const handleCheckIllegalWords = async (post: Post) => {
    try {
      const response = await fetch("/api/posts/check-illegal-words", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ content: post.content }),
      });

      const data = await response.json();
      if (data.illegalWords && data.illegalWords.length > 0) {
        setCheckedPosts((prev) => ({
          ...prev,
          [post.id]: data.illegalWords,
        }));
      }
    } catch (error) {
      console.error("检查敏感词失败:", error);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">帖子管理</h1>
        <p className="text-muted-foreground">查看和管理社区帖子信息</p>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-xl font-bold">帖子列表</CardTitle>
          <div className="flex items-center space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                type="search"
                placeholder="搜索帖子..."
                className="pl-8 w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Select value={categoryFilter} onValueChange={setCategoryFilter}>
              <SelectTrigger className="w-[150px]">
                <SelectValue placeholder="选择分类" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">所有分类</SelectItem>
                <SelectItem value="none">无分类</SelectItem>
                {categories.map((category) => (
                  <SelectItem
                    key={category.categoryId}
                    value={category.categoryId.toString()}
                  >
                    {category.categoryName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-[120px]">
                <SelectValue placeholder="选择状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">所有状态</SelectItem>
                <SelectItem value="0">已禁用</SelectItem>
                <SelectItem value="1">正常</SelectItem>
                <SelectItem value="2">已置顶</SelectItem>
              </SelectContent>
            </Select>
            <Button onClick={() => setIsCreateDialogOpen(true)}>
              <Plus className="mr-2 h-4 w-4" /> 新建帖子
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center items-center h-[400px]">
              <p>加载中...</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>发布者</TableHead>
                  <TableHead>内容</TableHead>
                  <TableHead>分类</TableHead>
                  <TableHead>发布时间</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>数据统计</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredPosts.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center h-24">
                      未找到匹配的帖子
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredPosts.map((post) => (
                    <TableRow
                      key={post.id}
                      className={
                        checkedPosts[post.id]?.length > 0 ? "bg-red-50" : ""
                      }
                    >
                      <TableCell className="font-medium">{post.id}</TableCell>
                      <TableCell>
                        {post.user && (
                          <div className="flex items-center space-x-2">
                            <img
                              src={post.user.avatarUrl}
                              alt={post.user.uName}
                              className="h-8 w-8 rounded-full object-cover"
                            />
                            <span>{post.user.uName}</span>
                          </div>
                        )}
                      </TableCell>
                      <TableCell>{truncateContent(post.content)}</TableCell>
                      <TableCell>
                        {post.category?.categoryName || "无分类"}
                      </TableCell>
                      <TableCell>{formatDate(post.createTime)}</TableCell>
                      <TableCell>
                        <Badge
                          variant={getPostStatusVariant(post.status) as any}
                        >
                          {getPostStatusText(post.status)}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {post.postCount && (
                          <div className="flex space-x-2 text-xs">
                            <span>浏览: {post.postCount.viewCount}</span>
                            <span>点赞: {post.postCount.likeCount}</span>
                          </div>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleCheckIllegalWords(post)}
                          title={
                            checkedPosts[post.id]
                              ? `包含敏感词：${checkedPosts[post.id].join(
                                  "、"
                                )}`
                              : "检查敏感词"
                          }
                        >
                          <AlertCircle
                            className={`h-4 w-4 ${
                              checkedPosts[post.id]?.length > 0
                                ? "text-red-500"
                                : ""
                            }`}
                          />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setSelectedPost(post);
                            setDialogOpen(true);
                          }}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setPostToDelete(post.id);
                            setIsDeleteDialogOpen(true);
                          }}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* 帖子详情对话框 */}
      <PostDialog
        post={selectedPost}
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        onSave={handlePostSave}
        categories={categories}
      />

      {/* 删除确认对话框 */}
      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              您确定要删除这个帖子吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={handleDeletePost}>
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 创建帖子对话框 */}
      <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>创建新帖子</DialogTitle>
            <DialogDescription>填写以下信息创建新的社区帖子</DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="category" className="text-right">
                分类
              </Label>
              <Select
                value={newPost.categoryId}
                onValueChange={(value) =>
                  setNewPost({ ...newPost, categoryId: value })
                }
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择分类" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">无分类</SelectItem>
                  {categories.map((category) => (
                    <SelectItem
                      key={category.categoryId}
                      value={category.categoryId.toString()}
                    >
                      {category.categoryName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-4 items-start gap-4">
              <Label htmlFor="content" className="text-right pt-2">
                内容
              </Label>
              <Textarea
                id="content"
                className="col-span-3 min-h-[100px]"
                placeholder="请输入帖子内容"
                value={newPost.content}
                onChange={(e) => {
                  setNewPost({ ...newPost, content: e.target.value });
                  setIllegalWordsError([]);
                }}
              />
              {illegalWordsError.length > 0 && (
                <div className="col-span-3 col-start-2 text-red-500 text-sm">
                  <p>内容包含敏感词：{illegalWordsError.join("、")}</p>
                </div>
              )}
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="images" className="text-right">
                图片链接
              </Label>
              <Input
                id="images"
                className="col-span-3"
                placeholder="多个图片链接请用分号(;)分隔"
                value={newPost.images}
                onChange={(e) =>
                  setNewPost({ ...newPost, images: e.target.value })
                }
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setIsCreateDialogOpen(false);
                setNewPost({
                  uId: "admin",
                  content: "",
                  categoryId: "",
                  images: "",
                });
                setIllegalWordsError([]);
              }}
            >
              取消
            </Button>
            <Button onClick={handleCreatePost}>创建</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
